package IO;

import java.io.*;
import java.util.Scanner;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-08-27
 * Time: 17:11
 */
public class Demo11 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入目标路径： ");
        String destFile = scanner.next();
        File file = new File(destFile);
        if(!file.isDirectory()) {
            System.out.println("输入路径有误!");
            return;
        }
        System.out.print("请输入你要寻找的关键字：");
        String key = scanner.next();
        scan(file,key);
    }
    private static void scan(File file, String key) {
        if(!file.isDirectory()) {
            return;
        }
        File[] files = file.listFiles();
        if(files == null || files.length == 0) {
            return;
        }
        for(File f : files) {
            if(f.isFile()) {
                doSerch(f,key);
            }else {
                scan(f,key);
            }
        }
    }
    private static void doSerch(File f, String key) {
        StringBuilder stringBuilder = new StringBuilder();

        try(Reader reader = new FileReader(f)) {

            while(true) {
                char[] buffer  = new char[1024];
                int n = reader.read(buffer);
                if(n == -1) {
                    break;
                }
                String s = new String(buffer,0,n);
                stringBuilder.append(s);
            }
        }catch(IOException e) {
            e.printStackTrace();
        }
        if(stringBuilder.indexOf(key) == -1) {
            return;
        }
        System.out.println("找到了匹配的文件：" +  f.getAbsolutePath());
    }
}
